using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Northwoods.Go;

namespace Workflows.Diagrams
{
    [Serializable()]
    public class PortMovingTool : GoTool
    {
        #region members
        private GoPort myPort = null;
        private SizeF myOffset = new SizeF();
        private PointF myOriginalPosition = new PointF();
        #endregion

        public PortMovingTool(GoView view)
            : base(view)
        {
        }

        public override void Start()
        {
            this.View.Cursor = Cursors.Cross;
            this.StartTransaction();
        }

        public override void Stop()
        {
            if ((this.myPort != null) && this.TransactionResult == null)
                this.myPort.Position = this.myOriginalPosition;
            this.StopTransaction();
            this.View.Cursor = this.View.DefaultCursor;
        }

        public override void DoMouseDown()
        {
            GoPort p = null;
            if (this.View.PickObject(true, false, this.LastInput.DocPoint, false).GetType() == typeof(GoPort))
            {
                p = (GoPort)this.View.PickObject(true, false, this.LastInput.DocPoint, false);
            }
            if (p != null)
            {
                this.myPort = p;
                this.myOffset = SubtractPoints(this.LastInput.DocPoint, p.Position);
                this.myOriginalPosition = this.myPort.Position;
            }
            else
            {
                this.StopTool();
            }
        }

        public override void DoMouseMove()
        {
            if (this.myPort != null)
            {
                PointF dp = this.LastInput.DocPoint;
                this.myPort.Position = new PointF(dp.X - this.myOffset.Width, dp.Y - this.myOffset.Height);
                ActivityNode node = null;
                if (this.myPort.ParentNode.GetType() == typeof(ActivityNode))
                    node = (ActivityNode)this.myPort.ParentNode;
                if (node != null)
                {
                    SizeF offset = SubtractPoints(this.myPort.Position, node.Icon.Position);
                    int spot = node.ComputePortLinkSpot(offset);
                    this.myPort.FromSpot = spot;
                    this.myPort.ToSpot = spot;
                }
            }
        }

        public override void DoMouseUp()
        {
            if (this.myPort != null)
            {
                this.myPort = null;
                this.TransactionResult = "moved port";
                this.StopTool();
            }
        }
    }
}
